package com.nch.haitonghop;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nch.haitonghop.data.DataManager;
import com.nch.haitonghop.data.SourceEntity;
import com.nch.haitonghop.others.RateRequestManager;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks, DataManager.DataManagerDelegate {

    static final String kWwwPrefix = "www.";

    private NavigationDrawerFragment mNavigationDrawerFragment;

    int selectedIndex = -1;
    SourceEntity currentSourceEntity;
    boolean isJustPressBackFistTime;

    WebView webview;
    RelativeLayout loadingView;
    AdView adView;
    Tracker tracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isJustPressBackFistTime = false;
        DataManager.getInstance().setDelegate(this);
        DataManager.getInstance().loadRemoteSource();

        setContentView(R.layout.activity_main);

        webview = (WebView)findViewById(R.id.main_webview);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
//                Log.d("", "Error load webpage : " + description);
                hideLoadingView();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                hideLoadingView();
            }
        });

        webview.getSettings().setJavaScriptEnabled(true);

        loadingView = (RelativeLayout)findViewById(R.id.main_loading_view);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));


        mNavigationDrawerFragment.selectCurrentItem();

        adView = (AdView)this.findViewById(R.id.adView);
        AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
        adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
        adRequestBuilder.addTestDevice("EEB3EC34691D85EFD1DF789EA3776326");
        adRequestBuilder.addTestDevice("00A7DB52F4CB9A60F07B1BF0BFE148DD"); //genymotion simulator
        AdRequest adRequest = adRequestBuilder.build();
        adView.loadAd(adRequest);

        RateRequestManager rateRequestManager = RateRequestManager.getInstance();
        rateRequestManager.setContext(this);
        rateRequestManager.setAppRateUrlString(getString(R.string.store_link));
        rateRequestManager.setCountToAskRate(10);
        rateRequestManager.updateAndShowRateRequestIfNeed();

        createTracker();
    }

    void createTracker() {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
        tracker = analytics.newTracker("UA-42372156-9");
    }

    void sendTrackerScreenName(String screenName) {
        if(tracker != null) {
            tracker.setScreenName(screenName);
            tracker.send(new HitBuilders.AppViewBuilder().build());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        adView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        adView.resume();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        setSelectedIndex(position);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        else if(id == R.id.action_refresh) {
            refreshWebView();
        }
        else if(id == R.id.action_scroll_top) {
            scrollWebViewToTop();
        }
        else if(id == R.id.action_scroll_bottom) {
            scrollWebViewToBottom();
        }

        return super.onOptionsItemSelected(item);
    }

    public void setSelectedIndex(int selectedIndex) {
        int oldSelectedIndex = this.selectedIndex;
        this.selectedIndex = selectedIndex;

        if(selectedIndex >= 0 && selectedIndex != oldSelectedIndex) {
            currentSourceEntity = DataManager.getInstance().getSourcesArray().get(selectedIndex);
            getSupportActionBar().setTitle(currentSourceEntity.title);
            webview.loadUrl(currentSourceEntity.link);
            showLoadingView();
            sendTrackerScreenName(currentSourceEntity.title);
        }
    }

    void showLoadingView() {
        loadingView.setVisibility(View.VISIBLE);
    }

    void hideLoadingView() {
        loadingView.setVisibility(View.GONE);
    }

    void refreshWebView() {
        String url = webview.getUrl();
        if(url != null && url.length() > 0) {
            webview.loadUrl(url);
            showLoadingView();
        }
        else {
            setSelectedIndex(selectedIndex);
        }
    }

    void scrollWebViewToTop() {
        webview.scrollTo(0, 0);
    }

    void scrollWebViewToBottom() {
        webview.scrollTo(0, webview.getContentHeight() - webview.getHeight());
    }

    @Override
    public void onNavigationDrawClose() {
        if(currentSourceEntity != null) {
            getSupportActionBar().setTitle(currentSourceEntity.title);
        }
    }

    @Override
    public void onNavigationDrawOpen() {

    }

    @Override
    public void onNavigationDrawAppInfoButtonClicked() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(R.string.app_info)
                .setMessage(R.string.app_info_message)
                .setNegativeButton(R.string.close, null)

                .setPositiveButton(R.string.rate, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.store_link)));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getApplicationContext().startActivity(intent);
                    }
                });
        builder.show();
    }

    @Override
    public void onBackPressed() {

        if(isUrlMatchRootUrl() || webview.canGoBack() == false) {
            if(isJustPressBackFistTime == true) {
                super.onBackPressed();
            }
            else {
                isJustPressBackFistTime = true;
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isJustPressBackFistTime = false;
                    }
                }, 3000);
                Toast.makeText(this, R.string.press_back_again_if_you_want_to_exit_app, Toast.LENGTH_SHORT).show();
                mNavigationDrawerFragment.openNavigationDraw();
            }
        }
        else {
            if(webview.canGoBack()) {
                webview.goBack();
            }
        }

    }

    boolean isUrlMatchRootUrl() {

        if(currentSourceEntity == null) {
            return false;
        }

        try {
            URL webViewUrl = new URL(webview.getUrl());
            URL rootUrl = new URL(currentSourceEntity.link);

            // First condition

            String webViewHost = webViewUrl.getHost();
            if(webViewHost.startsWith(kWwwPrefix)) {
                webViewHost = webViewHost.substring(kWwwPrefix.length());
            }

            String rootHost = rootUrl.getHost();
            if(rootHost.startsWith(kWwwPrefix)) {
                rootHost = rootHost.substring(kWwwPrefix.length());
            }

            if(webViewHost.equals(rootHost) == false) {
                return false;
            }

            // Second condition

            String webViewPath = webViewUrl.getPath();
            if(webViewPath.endsWith("/")) {
                webViewPath = webViewPath.substring(0, webViewPath.length() - 1);
            }

            String rootPath = rootUrl.getPath();
            if(rootPath.endsWith("/")) {
                rootPath = rootPath.substring(0, rootPath.length() - 1);
            }

            if(webViewPath.equals(rootPath) == false) {
                return false;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    public void dataManagerDidLoadRemoteSourceSuccess() {
        if(mNavigationDrawerFragment != null) {
            mNavigationDrawerFragment.notifyDataSetChange();
        }
    }

    @Override
    public void dataManagerDidLoadRemoteSourceFail() {

    }
}
